//获取图书
function renderCategory() {
  axios.get('/my/category/list').then(res => {
    let { status, data } = res.data;
    let str;
    data.forEach(item => {
      str += `	<tr>
   <td>${item.name}</td>
   <td>${item.alias}</td>
   <td>
     <button type="button" data-id='${item.id}' data-name='${item.name}' data-alias='${item.alias}' class="change layui-btn layui-btn-xs">编辑</button>
     <button type="button" data-id='${item.id}' class="del layui-btn layui-btn-xs layui-btn-danger">删除</button>
   </td>
 </tr>`
    })
    $('tbody').html(str)
  })
}
renderCategory()


//添加类别
let index;
$('.add').on('click', function () {
  index = layer.open({
    area: ['500px', '250px'],
    type: 1,
    title: '添加类别',
    content: $('#tpl-add').html(),
  });
})
$('body').on('submit', '#add-form', function (e) {
  e.preventDefault();
  let data = $(this).serialize();
  axios.post('/my/category/add', data).then(res => {
    let { status, message } = res.data;
    if (status === 0) {
      layer.msg(message);
      renderCategory()
      layer.close(index);
    }
  })
})
//编辑
let index1;
$('tbody').on('click', '.change', function () {
  let id = $(this).data('id');
  let name = $(this).data('name');
  let alias = $(this).data('alias');
  index1 = layer.open({
    area: ['500px', '250px'],
    type: 1,
    title: '编辑类别',
    content: $('#tpl-change').html(),
    success: function () {
      $('#change1').val(name);
      $('#change2').val(alias);
      $('#inp').val(id);
    }
  })

})

$('body').on('submit', '#change-form', function (e) {
  e.preventDefault();
  let data = $(this).serialize();
  axios.post('/my/category/update', data).then(res => {
    let { status, message } = res.data;
    if (status === 0) {
      layer.msg(message);
    
    }
    renderCategory()
    layer.close(index1);
  })

})


//删除
$('tbody').on('click', '.del', function () {
  let id = $(this).data('id');
  layer.confirm('你确定要删除我吗?', function (index) {
    //do something
    axios.get(`/my/category/delete?id=${id}`).then(res => {
      let { status, message } = res.data;
      if (status === 0) {
        layer.msg(message);
        renderCategory()
      }
    })

    layer.close(index);
  });
})

